<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>编辑--${site.name}</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="description" content="${site.description}"/>
    <meta name="keywords" content="${site.keywords}"/>
    <meta name="author" content="${site.author}"/>
    <link rel="icon" href="${site.logo}">
    <link rel="stylesheet" href="${base}/static/layui/css/layui.css" media="all"/>
    <style type="text/css">
        .layui-form-item .layui-inline {
            width: 33.333%;
            float: left;
            margin-right: 0;
        }

        @media (max-width: 1240px) {
            .layui-form-item .layui-inline {
                width: 100%;
                float: none;
            }
        }

        .layui-form-item .role-box {
            position: relative;
        }

        .layui-form-item .role-box .jq-role-inline {
            height: 100%;
            overflow: auto;
        }

    </style>
</head>
<body class="childrenBody">
<form class="layui-form" lay-filter="form" style="width:80%;">
    <input type="hidden" name="id" id="id" value="">
    <div class="layui-form-item">
        <label class="layui-form-label">学生学号</label>
        <div class="layui-input-block">
            <input type="text" class="layui-input layui-disabled" readonly="true" name="userNumber" id="userNumber"
                   value="">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">学生姓名</label>
        <div class="layui-input-block">
            <input type="text" class="layui-input layui-disabled" readonly="true" name="realName" id="realName"
                   value="">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">学期</label>
        <div class="layui-input-inline">
            <select name="paymentTerm" id="paymentTerm" class="submitlist" lay-verify="required">
                <option value="">请选择学期</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">本次缴费金额</label>
        <div class="layui-input-block">
            <input type="text" class="layui-input submitlist" name="paymentMoney" id="paymentMoney"
                   lay-verify="required" value=""
                   placeholder="本次缴费金额">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">剩余金额</label>
        <div class="layui-input-block">
            <input type="text" class="layui-input submitlist" name="paymentSpareMoney" id="paymentSpareMoney"
                   value="" placeholder="剩余金额">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">缴费日期</label>
        <div class="layui-input-inline">
            <input type="text" class="layui-input submitlist" name="paymentNowTime" id="paymentNowTime"
                   lay-verify="required"
                   value=""
                   placeholder="选择支付日期" readonly>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">下次缴费日期</label>
        <div class="layui-input-inline">
            <input type="text" class="layui-input submitlist" name="paymentNextTime" id="paymentNextTime"
                   value="" placeholder="选择下次支付日期" readonly>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">支付方式</label>
        <div class="layui-input-inline">
            <select name="paymentMode" id="paymentMode" autocomplete="off" class="submitlist" lay-verify="required"
                    lay-filter="paymode">
                <option value="">请选择支付方式</option>
            </select>
        </div>
        <div class="layui-input-inline">
            <select name="receivablesId" id="receivablesId" autocomplete="off" class="submitlist">
                <option value="">请选择账户</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">支付类型</label>
        <div class="layui-input-inline">
            <select name="paymentType" id="paymentType" class="submitlist" lay-filter="paymentType"
                    lay-verify="required">
                <option value="">请选择支付类型</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label lab">账单图片</label>
        <input type="hidden" id="imageUrl" name="imageUrl">
        <div class="layui-upload  layui-input-block">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-sm submitlist" type="button" id="selectvedio">选择文件</button>
            </div>
            <div class="layui-upload-list">
                <table class="layui-table">
                    <thead>
                    <tr>
                        <th>文件名</th>
                        <th>大小</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="upList"></tbody>
                </table>
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn submitlist" lay-submit="" lay-filter="addChPayment">立即提交</button>
            <button type="reset" class="layui-btn submitlist layui-btn-primary">重置</button>
        </div>
    </div>
</form>
<script type="text/javascript" src="${base}/static/layui/layui.js"></script>
<script type="text/javascript" src="${base}/static/js/qiniu.min.js"></script>
<script>
    layui.use(['form', 'jquery', 'layer', 'laydate', 'upload'], function () {
        var form = layui.form,
            $ = layui.jquery, laydate = layui.laydate,
            layer = layui.layer,
            upload = layui.upload;
        var paymentInfo = top.paymentInfo;

        form.val('form', {
            'id': paymentInfo.id,
            'userNumber': paymentInfo.userNumber,
            'paymentNowTime': paymentInfo.paymentNowTime,
            'paymentSpareMoney': paymentInfo.paymentSpareMoney / 100,
            'paymentNextTime': paymentInfo.paymentNextTime,
            'paymentMoney': paymentInfo.paymentMoney / 100,
            'receivablesId': paymentInfo.receivablesId,
            'realName': paymentInfo.realName
        });

        /**
         * 加载支付方式
         */
        $.get("${base}/admin/system/dict/getDictByType/pay_mode", {}, function (data) {
            var html = "<option value=\"\">请选择支付方式</option>";
            if (data.success === true) {
                for (var i = 0; i < data.data.length; i++) {
                    html += '<option value="' + data.data[i].value + '">' + data.data[i].label + '</option>';
                }
                $("#paymentMode").html(html);
                //表单重新渲染
                form.render();
                form.val('form', {
                    'paymentMode': paymentInfo.paymentMode
                })
            }
        }, "json");

        if (paymentInfo.receivablesAccount != null && paymentInfo.receivablesAccount != "") {
            $("#receivablesId").html("<option value=''>" + paymentInfo.receivablesAccount + "(" + paymentInfo.receivablesName + ")</option>");
        }


        form.on("select(paymode)", function (data) {
            var html = "<option value=''>请选择收款账户</option>";
            var payMode = data.value;
            if (payMode != 4 && payMode != 5) {
                $.ajax({
                    url: "${base}/chReceivables/getReceivablesByType",
                    type: 'post',
                    data: {payMode: payMode},
                    async: false,
                    datatype: 'json',
                    success: function (res) {
                        if (res.data != null) {
                            for (var i = 0; i < res.data.length; i++) {
                                html += "<option value='" + res.data[i].id + "'>" + res.data[i].receivablesAccount + "(" + res.data[i].receivablesName + ")" + "</option>"
                            }
                            $("#receivablesId").html(html);
                            form.render();
                        }
                    }
                })
            } else {
                $("#receivablesId").html("<option value=''>无收款账户</option>").attr("disabled", "true");
                form.render();
            }
        });


        /**
         * 加载支付类型
         */
        $.get("${base}/admin/system/dict/getDictByType/pay_type", {}, function (data) {
            var html = "<option value=\"\">请选择支付类型</option>";
            if (data.success === true) {
                for (var i = 0; i < data.data.length; i++) {
                    html += '<option value="' + data.data[i].value + '">' + data.data[i].label + '</option>';
                }
                $("#paymentType").html(html);
                //表单重新渲染
                form.render();
                form.val('form', {
                    'paymentType': paymentInfo.paymentType
                })
            }

        }, "json");

        /**
         * 加载学期
         */
        $.get("${base}/admin/system/dict/getDictByType/school_term", {}, function (data) {
            var html = "<option value=\"\">请选择学期</option>";
            if (data.success === true) {
                for (var i = 0; i < data.data.length; i++) {
                    html += '<option value="' + data.data[i].value + '">' + data.data[i].label + '</option>';
                }
                $("#paymentTerm").html(html);
                form.render();
                form.val('form', {
                    'paymentTerm': paymentInfo.paymentTerm
                })
            }

        }, "json");

        laydate.render({
            elem: '#paymentNowTime' //指定元素
            , type: 'datetime'
            , format: 'yyyy-MM-dd HH:mm:ss'
            , trigger: 'click'//可任意组合
        });

        laydate.render({
            elem: '#paymentNextTime' //指定元素
            , type: 'datetime'
            , format: 'yyyy-MM-dd HH:mm:ss'
            , trigger: 'click'//可任意组合
        });

        $.post("${base}/chPayment/getBillUrl", {'paymentId': paymentInfo.id}, function (data) {
            if (data.success == true && data.data != null) {
                $("#imageUrl").val(data.data);
                var tr = $(['<tr id="upload-' + 0 + '">'
                    , '<td id="rename">' + data.data + '</td>'
                    , '<td>' + '10kb' + '</td>'
                    , '<td><span id="ok" style="color: #00db4f;">已上传</span></td>'
                    , '<td>'
                    , '<button type="button" class="layui-btn layui-btn-xs demo-up layui-btn-normal layui-btn-disabled" style="display: none">上传</button>'
                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));
                $("#upList").append(tr);
                tr.find('.demo-delete').on('click', function () {
                    uploadListIns.config.elem.next()[0].value = '';
                    $("#imageUrl").attr("value", "");
                    tr.remove();
                    $("#selectvedio").removeClass('layui-btn-disabled').removeAttr("disabled");
                    <#--$.post("${base}/chPayment/deleteBill", {-->
                        <#--'key': data.data,-->
                        <#--"id": paymentInfo.id-->
                    <#--}, function (data) {-->
                        <#--if (data.success == true) layer.msg("删除成功");-->
                        <#--else layer.msg(data.message)-->
                    <#--});-->
                });
                $("#selectvedio").addClass('layui-btn-disabled').attr('disabled', "true");
            } else {
                layer.msg(data.message);
            }
        }, 'json');

        //初始化文件上传事件（七牛云）
        var uploadListIns = upload.render({
            elem: "#selectvedio",
            accept: "images",
            multiple: false,
            auto: false,
            choose: function (obj) {
                var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                //读取本地文件
                obj.preview(function (index, file, result) {
                    var tr = $(['<tr id="upload-' + index + '">'
                        , '<td>' + file.name + '</td>'
                        , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                        , '<td>等待上传</td>'
                        , '<td>'
                        , '<button type="button" class="layui-btn layui-btn-xs demo-up layui-btn-normal" style="display:none;">上传</button>'
                        , '<button class="layui-btn layui-btn-xs submitlist layui-btn-danger  demo-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));

                    //单个上传
                    tr.find('.demo-up').on('click', function () {
                        //接收token
                        var token = "";
                        //接受随机文件名
                        var rondomName = "";
                        var suffix = file.name.substring(file.name.lastIndexOf("."), file.name.length);//获取文件后缀
                        // obj.upload(index, file);
                        $.ajax({
                            type: 'post',
                            url: "${base}/chPayment/getUploadToken",
                            data: {"suffix": suffix},
                            async: false,
                            dataType: 'json',
                            success: function (res) {
                                console.log(res);
                                if (res.success) {
                                    token = res.data.token;
                                    rondomName = res.data.filename;//随机文件名
                                } else {
                                    layer.msg(res.message);
                                    delete files[index]; //删除对应的文件
                                    $("#selectvedio").removeClass('layui-btn-disabled').removeAttr("disabled");
                                    tr.remove();
                                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                                }
                            }
                        });
                        fileUpload(index, file, token, rondomName);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        $("#imageUrl").val("");
                        $("#selectvedio").removeClass('layui-btn-disabled').removeAttr("disabled");
                        uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                    });
                    var num = index.split("-")[1];
                    num = parseInt(num);
                    if (num < 1) {
                        $("#selectvedio").addClass('layui-btn-disabled').attr('disabled', "true");
                        $("#imageUrl").attr("value", "new");
                        $("#upList").append(tr);
                    }
                });
            }
        });

        /**
         * 上传七牛云核心代码
         * @param index 文件下表
         * @param file  文件对象
         * @param token 凭证
         * @param randomName 接口生成的随机文件名，之后用来当作文件地址
         */
        function fileUpload(index, file, token, randomName) {

            var fileName = file.name;                                //上传的本地文件绝对路径
            var size = file.size > 1024 ? file.size / 1024 > 1024 ? file.size / (1024 * 1024) > 1024 ? (file.size / (1024 * 1024 * 1024)).toFixed(2) + 'GB' : (file.size
                / (1024 * 1024)).toFixed(2) + 'MB' : (file.size
                / 1024).toFixed(2) + 'KB' : (file.size).toFixed(2) + 'B';		//文件上传大小
            var tr = $("#upList").find("tr#upload-" + index);
            var tds = tr.children();
            //七牛云上传
            var observer = {                         //设置上传过程的监听函数
                next(res) {                        //上传中(result参数带有total字段的 object，包含loaded、total、percent三个属性)
                    var upview = Math.floor(res.total.percent); //查看进度[loaded:已上传大小(字节);total:本次上传总大小;percent:当前上传进度(0-100)]
                    tds.eq(2).html('<span style="color: #c1c20c;">正在上传-(' + upview + '%) </span>');


                },
                error(err) {
                    tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');  //失败后

                },
                complete(res1) {                      //成功后
                    //****:填写你的绑定域名或七牛云提供的测试域名
                    //?imageView2/2/h/100：展示缩略图，不加显示原图
                    tds.eq(0).html(randomName);
                    tds.eq(2).html('<span style="color: #00db4f;">上传成功</span>');
                    $("#imageUrl").val(randomName);
                    formdata.field.imageUrl = randomName;
                    var addIndex = parent.layer.getFrameIndex(window.name);
                    $.post("${base}/chPayment/edit", formdata.field, function (res) {
                        if (res.success) {
                            parent.layer.msg("修改成功！", {time: 1000}, function () {
                                parent.layer.close(addIndex);
                                //刷新父页面
                                parent.layui.table.reload('test');
                            });
                        } else {
                            layer.msg(res.message);
                        }
                    });
                }
            };
            var putExtra = {
                fname: randomName,                          //原文件名
                params: {},                         //用来放置自定义变量
                mimeType: null                      //限制上传文件类型
            };
            var config = {             //存储区域(z0: 代表华东;不写默认自动识别)
                concurrentRequestLimit: 3            //分片上传的并发请求量
            };
            var observable = qiniu.upload(file, randomName, token, putExtra, config);
            observable.subscribe(observer)          // 上传开始
        }


        var formdata;
        form.on("submit(addChPayment)", function (data) {
            if ($("#upList").find("tr").length > 1) {
                layer.msg("只能上传一张账单！！！", {anim: 4});
                return false;
            }
            formdata = data;
            if (data.field.paymentTime < data.field.paymentNextTime) {
                layer.msg("下次付款日期不能小于当前日期！", {time: 1000}, function () {
                    return false;
                });
            }
            var addIndex = parent.layer.getFrameIndex(window.name);
            $(".submitlist").addClass('layui-btn-disabled').attr('disabled', "true");
            if ($("#imageUrl").val() != "new") {
                $.post("${base}/chPayment/edit", data.field, function (res) {
                    if (res.success) {
                        parent.layer.msg("修改成功！", {time: 1000}, function () {
                            parent.layer.close(addIndex);
                            //刷新父页面
                            parent.layui.table.reload('test');
                        });
                    } else {
                        layer.msg(res.message);
                    }
                });
            } else {
                $(".demo-up").click();
            }
            return false;
        });
    });
</script>
</body>
</html>